<template>
  <div class="app-container">
    <ToolBar :filters="filters" :getList="getList" :handleAdd="handleCreate"/>
    <el-table v-loading="listLoading" :data="userList" element-loading-text="Loading" border fit highlight-current-row>
      <el-table-column align="center" label="ID" width="95" type="index"></el-table-column>
      <el-table-column prop="username" label="用户名" align="center"></el-table-column>
      <el-table-column prop="name" label="姓名" width="95" align="center"></el-table-column>
      <el-table-column prop="mobilephone" label="联系电话" align="center"></el-table-column>
      <el-table-column prop="roleName" label="角色" align="center"></el-table-column>
      <el-table-column label="操作" fixed="right" width="300" align="center">
        <template slot-scope="scope">
          <el-button size="small" type="warning" @click="handleUpdate(scope.$index, scope.row)">
            <i class="el-icon-edit"></i>
          </el-button>
          <el-button type="danger" size="small" icon="el-icon-delete" @click="handleDel(scope.$index, scope.row)"></el-button>
        </template>
      </el-table-column>
    </el-table>
    <!--翻页-->
    <el-col :span="24" class="toolbar">
      <Pagination v-show="total>0" :total="total" :pageSize="pagesize" :handleCurrentChange="handleCurrentChange"/>
    </el-col>
    <!--弹窗界面-->
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" :close-on-click-modal="false">
      <el-form label-width="100px" :model="Form" :rules="FormRules" ref="dataForm">
        <el-form-item label="姓名" prop="name" width="100%">
          <el-input v-model="Form.name"></el-input>
        </el-form-item>
        <el-form-item label="用户名" prop="username" width="100%">
          <el-input v-model="Form.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password" width="100%">
          <el-input type="password" v-model="Form.password"></el-input>
        </el-form-item>
        <el-form-item label="联系方式" prop="mobilephone" width="100%">
          <el-input v-model="Form.mobilephone"></el-input>
        </el-form-item>
        <el-form-item label="所属客户" prop="customerId">
          <el-select v-model="Form.customerId" class="filter-item" placeholder="请选择所属客户">
            <el-option v-for="item in customersOptions" :key="item.customerId" :label="item.customerName" :value="item.customerId"/>
          </el-select>
        </el-form-item>
        <el-form-item label="用户角色" prop="roles">
          <el-checkbox-group v-model="Form.roles">
            <el-checkbox v-for="item in roleOptions" :label="item.roleId" :key="item.roleId">{{item.roleName}}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import {
  getUserList,
  getUserData,
  createUser,
  updateUser,
  deleteUser,
  getRoleTypes,
  getRole
} from "@/api/users";
import { getCustomerAll } from "@/api/customers";
import ToolBar from "@/views/layout/components/ToolBar";
import Pagination from "@/views/layout/components/Pagination";
import { isvalidPhone } from "@/utils/validate";
import { mapGetters, mapActions } from "vuex";
const validPhone = (rule, value, callback) => {
  if (!value) {
    callback(new Error("请输入电话号码"));
  } else if (!isvalidPhone(value)) {
    callback(new Error("请输入正确的11位手机号码"));
  } else {
    callback();
  }
};
export default {
  components: { ToolBar, Pagination },
  data() {
    return {
      filters: {
        name: "",
        placeholder: "用户名称"
      },
      userList: [],
      customersOptions: [],
      roleOptions: [],
      listLoading: false,
      total: 0,
      pagesize: 10,
      dialogStatus: "",
      textMap: {
        update: "编辑用户",
        create: "新增用户"
      },
      dialogFormVisible: false,
      Form: {
        name: "",
        username: "",
        password: "",
        customerId:null,
        roleType: [],
        mobilephone: ""
      },
      FormRules: {
        name: [{ required: true, message: "请输入姓名", trigger: "blur" }],
        username: [ { required: true, message: "请输入用户名", trigger: "blur" }],
        password: [{ required: true, message: "请输入密码", trigger: "blur" }],
        customerId: [{ required: true, message: "请选择所属客户", trigger: "change" }],
        roles: [{ required: true, message: "请选择用户角色", trigger: "blur" }],
        mobilephone: [ { required: true, trigger: "blur", validator: validPhone }]
      }
    };
  },

  created() {
    this.getList();
    this.getRoleCode();
    this.getCustomerCode();
  },
  methods: {
    // 获取用户角色
    getRoleCode() {
      getRoleTypes().then(response => {
        this.roleOptions = response.data.map(item => {
          return { roleId: item.id, roleName: item.roleName };
        });
      });
    },
    // 获取客户
    getCustomerCode() {
      getCustomerAll().then(response => {
        this.customersOptions = response.data.map(item => {
          return { customerId: item.id, customerName: item.customerName };
        });
      });
    },

    getList() {
      this.listLoading = true;
      getUserList({
        name: this.filters.name,
        page: this.page,
        size: this.pagesize
      })
        .then(response => {
          this.userList = response.data;
          this.total = response.data.total;
          this.listLoading = false;
        })
        .catch(e => {});
    },
    // 翻页
    handleCurrentChange(val) {
      this.page = val;
      this.getList();
    },

    //重置form
    resetForm() {
      this.Form = {
        name: "",
        username: "",
        password: "",
        customerId:null,
        roles: [],
        mobilephone: ""
      };
    },
    //新建Form弹窗
    handleCreate() {
      this.resetForm();
      this.dialogStatus = "create";
      this.dialogFormVisible = true;
      this.$nextTick(() => {
        this.$refs.dataForm.clearValidate();
      });
    },

    createData() {
      this.$refs["dataForm"].validate(valid => {
        if (valid) {
          createUser(this.Form).then(() => {
            this.getList();
            this.dialogFormVisible = false;
            this.$notify({
              title: "成功",
              message: "创建成功",
              type: "success",
              duration: 2000
            });
          });
        }
      });
    },

    //显示编辑界面
    handleUpdate(index, row) {
      this.resetForm();
      getRole({ id: row.id }).then(response => {
        this.Form.roles = response.data;
      });
      this.Form = Object.assign(this.Form, row);
      this.dialogStatus = "update";
      this.dialogFormVisible = true;
      this.$nextTick(() => {
        this.$refs.dataForm.clearValidate();
      });
    },
    //编辑数据
    updateData() {
      this.$refs["dataForm"].validate(valid => {
        if (valid) {
          const tempData = Object.assign({}, this.Form);
          updateUser(tempData).then(() => {
              this.getList();
            this.dialogFormVisible = false;
            this.$notify({
              title: "成功",
              message: "更新成功",
              type: "success",
              duration: 2000
            });
          });
        }
      });
    },

    handleDel(index,row) {
      this.$confirm("确认删除该用户吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(()=>{
        this.listLoading = true;
        deleteUser({id:row.id}).then(() => {
           this.getList();
          this.listLoading = false;
          this.$notify({
            title: '成功',
            message: '删除成功',
            type: 'success',
            duration: 2000
           })
         })

      }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
      
    },
  }
};
</script>

